import React, {
    useState,
    useMemo,
    useEffect,
    useContext,
    Fragment,
} from 'react';
import { Menu, Checkbox, Dropdown, Button, Space, Input, Empty } from 'antd';
import { SearchOutlined } from '@ant-design/icons';

import { HcpTableContext } from '../HcpTable/HcpTable';
import './HcpColumnsFilter.less';
/**
*
* @param {*} { type }
* @param {*} { dataSource }
* @param {*} { handleChange }
* @returns
*/
const HcpColumnsFilter = ({ name, dataSource, handleChange }) => {
    const style = {
        width: '100vw',
        height: '100vh',
        position: 'fixed',
        top: 0,
        left: 0,
        zIndex: 1,
    };

    const [checkAll, setCheckAll] = useState(false);
    const [boxData, setBoxData] = useState([]);
    const [oldBoxData, setOldBoxData] = useState([]);
    const [visible, setVisible] = useState(false);
    const [isint, setIsint] = useState(true);
    const [selectLength, setSelectLength] = useState(0);
    const [search, setSearch] = useState('');

    useEffect(() => {
        if (visible) {
            setOldBoxData(boxData);
        }
        if (!isint && !visible) {
            if (boxData != oldBoxData) {
                handleSubmit();
            }
        } else {
            setIsint(false);
        }
    }, [visible]);

    useEffect(() => {
        let arr = [];
        let data = dataSource ? JSON.parse(JSON.stringify(dataSource)) : dataSource;
        if (data) {
            arr = data.map((item, index) => {
                // 如果传进来checked标志，设默认值
                item.isShow = item.isShow ?? true;
                item.checked = item.checked ?? false;
                item.key = index;
                return item;
            });
        }
        setBoxData(arr);
        //  是否选择逻辑
        let bool = arr.filter((item) => {
            return item.checked;
        });
        setSelectLength(bool.length);
        // 全选逻辑
        if (bool?.length == data?.length) {
            setCheckAll(true);
        } else {
            setCheckAll(false);
        }
        if (bool?.length > 0) handleSubmit(bool); // 初始化时存在选中状态则
        // 触发visible
        setVisible(false);
    }, [dataSource]);

    // 获取表头筛选重置的状态
    const colReset = useContext(HcpTableContext);

    useEffect(() => {
        if (colReset) {
            setSelectLength(0);
            resetFileter();
        }
    }, [colReset]);

    // 重置
    const resetFileter = () => {
        boxData.filter((item) => {
            item.checked = false;
        });
        setBoxData(JSON.parse(JSON.stringify(boxData)));
        setCheckAll(false);
        setSearch('');
        if (handleChange) handleChange([]);
    };
    // 单选
    const onChange = (e, key) => {
        boxData.find(i => i.key == key).checked = e.target.checked;
        handleCheckAll(boxData);
        setBoxData(JSON.parse(JSON.stringify(boxData)));
    };
    // 全选
    const onCheckAllChange = (e) => {
        setCheckAll(e.target.checked);
        boxData.filter((item) => {
            if (item.isShow)
                item.checked = e.target.checked;
        });
        setBoxData(JSON.parse(JSON.stringify(boxData)));
    };
    // 隐藏触发
    const handleSubmit = (b) => {
        let bool = b ? b : boxData.filter((item) => {
            return item.checked;
        });
        setSelectLength(bool.length);
        if (handleChange) handleChange(bool);
    };

    // 搜索
    useEffect(() => {
        let value = search.trim();
        setBoxData(data => {
            let checkAll = true;
            let arr = data.map(item => {
                if (item.text.indexOf(value) > -1)
                    item.isShow = true;
                else
                    item.isShow = false;
                return item;
            })
            handleCheckAll(arr);
            return arr;
        })
    }, [search])

    const handleCheckAll = (data) => {
        let showNum = 0, checkedNum = 0;
        data.forEach(item => {
            if (item.isShow) showNum++;
            if (item.isShow && item.checked) checkedNum++;
        })
        if (showNum == checkedNum && checkedNum != 0)
            setCheckAll(true);
        else
            setCheckAll(false);
    }

    return (
        <Fragment>
            <Dropdown
                overlay={
                    <>
                        {
                            boxData.length > 9 &&
                            <div className="hcp_colimns_filter_search">
                                <Input placeholder="在筛选项中搜索" value={search} onChange={(e) => { setSearch(e.target.value) }} prefix={<SearchOutlined />} />
                            </div>
                        }
                        <Menu className="hcp_colimns_filter">
                            <Menu.Item key="all">
                                <Checkbox
                                    checked={checkAll}
                                    onChange={(e) => {
                                        onCheckAllChange(e);
                                    }}
                                >
                                    全部
                                </Checkbox>
                            </Menu.Item>
                            <Menu.ItemGroup
                                key="1"
                                style={{ maxHeight: 300, overflowY: 'auto' }}
                            >
                                {boxData.filter(item => item?.isShow).length > 0
                                    ? boxData.filter(item => item.isShow).map(item => {
                                        return (
                                            <Menu.Item key={item.key}>
                                                <Checkbox
                                                    checked={item.checked}
                                                    onChange={(e) => {
                                                        onChange(e, item.key);
                                                    }}
                                                >
                                                    {item.text}
                                                </Checkbox>
                                            </Menu.Item>
                                        );
                                    })
                                    : <div className='empty'>暂无数据</div>}
                            </Menu.ItemGroup>
                            <Menu.Item key="handle" className="text-center">
                                <Space>
                                    <Button
                                        type="primary"
                                        size="small"
                                        onClick={() => {
                                            setVisible(false);
                                        }}
                                    >
                                        确定
                                    </Button>
                                </Space>
                            </Menu.Item>
                        </Menu>
                    </>
                }
                trigger={['click']}
                visible={visible}
            >
                <span>
                    <span className="cell_name">{name}</span>
                    <span
                        className={
                            `iconfont icon-filter ${selectLength
                                ? 'table-filterIcon-has'
                                : 'table-filterIcon'}`
                        }
                        onClick={() => {
                            setVisible(true);
                        }}
                    />
                </span>
            </Dropdown>
            {visible && (
                <div
                    style={style}
                    onClick={() => {
                        setVisible(false);
                    }}
                />
            )}
        </Fragment>
    );
};

export default HcpColumnsFilter;
